package com.zxjbyte.yiyi.framework.web.context;

import cn.hutool.crypto.asymmetric.AsymmetricDecryptor;
import cn.hutool.crypto.asymmetric.AsymmetricEncryptor;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.symmetric.SymmetricDecryptor;
import cn.hutool.crypto.symmetric.SymmetricEncryptor;

/**
 * 加解密算法枚举
 * @Author zhangxingjia
 * @Date 2025/11/1 14:43
 * @Version: 1.0
 */
public enum CryptoAlgorithm {
    AES,
    RSA,
    SM4;  // 国密算法

    /**
     * 加密数据
     * @param data 原始数据
     * @param cryptoInstance 加密器实例
     * @return 加密后的数据
     */
    public String encrypt(byte[] data, Object cryptoInstance) {
        return doEncrypt(data, cryptoInstance, isAsymmetricAlgorithm());
    }

    /**
     * 解密数据
     * @param encryptedData 加密数据
     * @param cryptoInstance 加密器实例
     * @return 解密后的数据
     */
    public byte[] decrypt(String encryptedData, Object cryptoInstance) {
        return doDecrypt(encryptedData, cryptoInstance, isAsymmetricAlgorithm());
    }

    /**
     * 执行加密操作
     */
    private String doEncrypt(byte[] data, Object cryptoInstance, boolean isAsymmetric) {
        if (isAsymmetric) {
            // 非对称加密器
            AsymmetricEncryptor asymmetricEncryptor = (AsymmetricEncryptor) cryptoInstance;
            return asymmetricEncryptor.encryptBase64(data, KeyType.PublicKey);
        } else {
            // 对称加密器
            SymmetricEncryptor symmetricEncryptor = (SymmetricEncryptor) cryptoInstance;
            return symmetricEncryptor.encryptBase64(data);
        }
    }

    /**
     * 执行解密操作
     */
    private byte[] doDecrypt(String encryptedData, Object cryptoInstance, boolean isAsymmetric) {
        if (isAsymmetric) {
            AsymmetricDecryptor asymmetricDecryptor = (AsymmetricDecryptor) cryptoInstance;
            return asymmetricDecryptor.decrypt(encryptedData, KeyType.PrivateKey);
        } else {
            SymmetricDecryptor symmetricDecryptor = (SymmetricDecryptor) cryptoInstance;
            return symmetricDecryptor.decrypt(encryptedData);
        }
    }

    /**
     * 判断是否为非对称加密算法
     */
    private boolean isAsymmetricAlgorithm() {
        return this == RSA;
    }

    /**
     * 判断是否为对称加密算法
     */
    public boolean isSymmetricAlgorithm() {
        return this != RSA;
    }
}
